package com.sgb.kjwl.viewmodel.supplier3;

import android.annotation.SuppressLint;
import android.text.TextUtils;

import androidx.core.util.Pair;

import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.EnquiryImAlternateEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.manage.WebsiteInfoEntity;
import com.sgb.kjwl.model.entity.self.PermissionMenuEntity;
import com.sgb.kjwl.model.entity.supplier3.SupplierRecommendEntity;
import com.sgb.kjwl.repository.HomeRepertory;
import com.sgb.kjwl.view.ui.activity.supplier3.NewSupplierFragment;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.entity.MenuEntity;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author Administrator
 */
public class SupplierFragmentModel extends BaseViewModel {
    private final NewSupplierFragment supplierFragment;
    private final HomeRepertory repertory;
    private int page = 1;
    public List<PermissionMenuEntity> list = new ArrayList<>();

    public SupplierFragmentModel(NewSupplierFragment supplierFragment, HomeRepertory repertory) {
        this.supplierFragment = supplierFragment;
        this.repertory = repertory;
    }

    @SuppressLint("CheckResult")
    public void getDistanceModel() {
        repertory.getDistance()
                .subscribe(listBaseEntity -> {
                    if (listBaseEntity.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                        supplierFragment.showDistancePopWindow(listBaseEntity.getData());
                    }
                }, throwable -> MLog.d(AppConstant.API_LOG, "error " + throwable.getMessage()));
    }

    /**
     * 获取供货商列表数据
     *
     * @param map
     * @param isLoadMore
     */
    @SuppressLint("CheckResult")
    public void getSupplierListModel(Map map, boolean isLoadMore) {
        page = isLoadMore ? page + 1 : 1;
        map.put("page", page);
        map.put("current", page);
        int size = 20;
        map.put("limit", size);
        DialogHelper.showProgressDialog2(supplierFragment.getContext(), null, "获取信息中...", 0, false, null, false);
        repertory.getSupplierMapData(map).subscribe(listResponseBaseEntity -> {
            DialogHelper.dismissProgressDialog();
            if (listResponseBaseEntity.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                supplierFragment.showList(listResponseBaseEntity.getData().getList(), isLoadMore);
                supplierFragment.showMap(listResponseBaseEntity.getData().getList(), isLoadMore);
            }
        }, throwable -> {
            DialogHelper.dismissProgressDialog();
            MLog.d(AppConstant.API_LOG, "error " + throwable.getMessage());
        });
    }

    public void getWebsiteInfo(Map<String, String> map, String websiteNo, int type) {
        DialogHelper.showProgressDialog2(supplierFragment.getActivity(), null, "数据加载中...", 0, false, null, false);
        APIManager.getInstance().getWebsiteInfoAPI().getSiteInfo(map).enqueue(new ICallBack<BaseEntity<WebsiteInfoEntity>>() {
            @Override
            public void onSuccess(BaseEntity<WebsiteInfoEntity> data) {
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    if (data.getData() == null) {
                        MToast.showToast(supplierFragment.getActivity(), TextUtils.isEmpty(data.getMsg()) ? "当前未查询到网站详情" : data.getMsg());
                        return;
                    }
                    supplierFragment.showWebsiteInfo(data.getData(), websiteNo, type);
                }
            }

            @Override
            public void onFail() {
                super.onFail();
            }
        });
    }


    public void getPermissionMenu(WebsiteInfoEntity entity, int websiteType, String websiteNo, String companyName, int type) {
        String companyNo;
        if (websiteType == 0) {
            companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
        } else {
            companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        }
        if (!TextUtils.isEmpty(companyNo)) {
            getBottomPermission(entity, websiteType, websiteNo, companyName, type);
        }
    }

    private void getBottomPermission(WebsiteInfoEntity entity, int websiteType, String websiteNo, String companyName, int type) {
        supplierFragment.getPermission(entity, websiteType, websiteNo, companyName, type);
    }

    /**
     * 获取商品ImAccount
     *
     * @param userNo
     */
    public void getGoodsImAccount(String userNo,int type) {
        DialogHelper.showProgressDialog2(supplierFragment.getActivity(), null, "数据加载中...", 0, false, null, false);
        NewAPIManager.getInstance().getCommonAPI().itemImAlternate(userNo, type).enqueue(new Callback<BaseEntity<EnquiryImAlternateEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<EnquiryImAlternateEntity>> call, Response<BaseEntity<EnquiryImAlternateEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if (response.body().getData().getConfirmType() != null && 2 == response.body().getData().getConfirmType()) {
                        if (!TextUtils.isEmpty(response.body().getData().getConfirmMessage())) {
                            MToast.showToast(supplierFragment.getActivity(), response.body().getData().getConfirmMessage());
                        }
                    } else {
                        List<EnquiryImAlternateEntity.CompanyCustomersDTO> companyCustomers = response.body().getData().getCompanyCustomers();
                        if (companyCustomers != null) {
                            supplierFragment.showImWindow(companyCustomers);
                        }
                    }
                } else {
                    MToast.showToast(supplierFragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<EnquiryImAlternateEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //1.5.7 商品首页询价新增token失效的校验，后端提议用这个接口来判断
    public void getCheckUserInfo(SupplierRecommendEntity entity) {
        DialogHelper.showProgressDialog(supplierFragment.getContext(), null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().getUserInfo().enqueue(new Callback<BaseEntity<UserMsgEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<UserMsgEntity>> call, Response<BaseEntity<UserMsgEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getData() == null) return;
                if (response.body().getState().equals("ok")) {
                    supplierFragment.buildInquirySupplierParam(entity);
                } else {
                    MToast.showToast(supplierFragment.getContext(), "登录过期,请重新登录");
                    ActivityJump.startActivity(AppRouteConstant.VerificationCodeLoginActivity, Pair.create("isJump", false));
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<UserMsgEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }


    public void getMenuModel() {
        DialogHelper.showProgressDialog(supplierFragment.getActivity(), null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);

        Map map = new HashMap<String,Object>();
        if (map == null) {
            map = new HashMap(2);
        }
        map.put("areaCode", repertory.getAreaCode());
        APIManager.getInstance().getMaterialAPI().getItemCatList(map).enqueue(new Callback<BaseEntity<List<MenuEntity>>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<List<MenuEntity>>> call, @NotNull Response<BaseEntity<List<MenuEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    supplierFragment.showecommendCategoryData(response.body().getData());
                } else {
                    MToast.showToast(supplierFragment.getActivity(), response.message());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<List<MenuEntity>>> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(supplierFragment.getActivity(), t.getMessage());
            }
        });
    }
}
